import { mobile, detectPassword } from '@/common/test'
import { name } from '@/common/config'
import uploadsFile from './uploadsFile.js'
// #ifdef APP-PLUS
const dom = weex.requireModule('dom')
// #endif
import store from '@/store'
import { preloadData } from '../vehicle/list'

// 格式化时间
export function dateFormat(date = new Date(), fmt = 'YYYY-MM-DD') {
  if (typeof date === 'string') date = date.replace(/-/g, '/')
  const time = new Date(date)
  const weekArr = ['日', '一', '二', '三', '四', '五', '六']
  var o = {
    'M+': time.getMonth() + 1, // 月份
    'D+': time.getDate(), // 日
    'h+': time.getHours(), // 小时
    'm+': time.getMinutes(), // 分
    's+': time.getSeconds(), // 秒
    'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
    S: time.getMilliseconds(), // 毫秒
    W: time.getDay() // 星期
  }
  if (/(Y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length)) }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1 == 'W'
          ? weekArr[o[k]]
          : RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}

// 获取系统信息
export function sysInfo() {
  return uni.getSystemInfoSync()
}

// toast弹窗
export function toast(title, fn, duration = 1500, mask = false, icon = 'none', position = 'bottom') {
  if (store.getters.showToast) {
    setTimeout(() => {
      store.commit('user/setShowToast', false)
    }, duration)
    return
  }
  store.commit('user/setShowToast', true)
  uni.showToast({
    title,
    icon,
    duration,
    position,
    mask,
    success: () => {
      setTimeout(() => {
        store.commit('user/setShowToast', false)
        if (fn) fn()
      }, duration)
    }
  })
}

// loading弹窗
export function loading(title, fn, mask = true) {
  uni.showLoading({
    title,
    mask,
    success: () => {
      if (fn) fn()
    }
  })
  return {
    hide: () => {
      uni.hideLoading()
    }
  }
}

// 权限验证跳转
export function jump(url, type, passport = false) {
  // 是否登录验证
  if (!store.getters.token && passport) {
    toast('请先登录')
    return
  }
  // 跳转
  if (url && typeof url === 'string') {
    switch (type) {
      case 'redirectTo':
        uni.redirectTo({
          url
        })
        break
      case 'reLaunch':
        uni.reLaunch({
          url
        })
        break
      case 'switchTab':
        uni.switchTab({
          url
        })
        break
      default:
        uni.navigateTo({
          url
        })
        break
    }
  } else {
    if (url > 1) uni.navigateBack({ delta: url })
    else uni.navigateBack()
  }
}

// 获取元素数据
export function getElementInfo(select, fn, that) {
// #ifndef APP-NVUE
  let element
  if (select.indexOf('.') !== -1) {
    element = that ? uni.createSelectorQuery().in(that).selectAll(select) : uni.createSelectorQuery().selectAll(select)
  } else {
    element = that ? uni.createSelectorQuery().in(that).select(select) : uni.createSelectorQuery().select(select)
  }
  element.boundingClientRect(res => {
    fn(res)
  }).exec()
  // #endif

  // #ifdef APP-NVUE
  let el = typeof select === 'string' ? that.$refs[select.substr(1)] : select
  if (Array.isArray(el)) el = el[0]
  dom.getComponentRect(el, res => {
    fn(res.size)
  })
  // #endif
}

// 下载文件
export function downloadFile(url) {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 保存文件
export function saveFile(tempFilePath) {
  uni.saveFile({
    tempFilePath,
    success(res) {
      toast('下载成功，文件保存在' + res.savedFilePath,)
    }
  })
}

// 上传单张图片
export function saveImage(dir) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: (res) => {
        const filePath = res.tempFilePaths
        const size = res.tempFiles[0].size
        if (size > 1024 * 1024 * 10) {
          toast('文件过大请重新选择')
          reject({
            title: '',
            msg: '文件过大请重新选择',
            code: 1024
          })
        } else {
          uploadsFile(filePath, dir).then(data => {
            resolve(data[0])
          })
        }
      },
      fail: err => {
        let content = `在设置-应用-${name}车企-权限中开启`
        if (err.code === 12) {
          // 相册
          content += '储存空间权限'
        }
        if (err.code === 11) {
          // 拍照
          content += '相机权限'
        }
        if (err.code === 11 || err.code === 12) {
          reject({
            title: '权限申请',
            msg: content,
            code: 1025
          })
        }
      }
    })
  })
}

// 打开设置
export function openSetting() {
  // 打开小程序的设置
  // #ifdef MP
  uni.openSetting()
  // #endif

  // App跳转系统的设置界面
  // #ifdef APP-PLUS
  const info = uni.getSystemInfoSync()
  if (info.platform == 'ios') { // IOS
    plus.runtime.openURL('app-settings://')
  } else if (info.platform == 'android') { // 安卓
    const main = plus.android.runtimeMainActivity()
    const Intent = plus.android.importClass('android.content.Intent')
    const Settings = plus.android.importClass('android.provider.Settings')
    const Uri = plus.android.importClass('android.net.Uri')
    const uri = new Uri().fromParts('package', 'com.tbb.company', null)
    const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri)
    main.startActivity(intent)
  }
  // #endif
}

// 查看图片
export function viewImage(current, urls, loop = false, type = 'number') {
  let indicator = 'none'
  
  if (urls.length > 1) indicator = type
  urls = urls.filter(ur => ur && ur !== '暂无')
  if(urls.length <= 0) return false;
  uni.previewImage({
    current,
    urls,
    indicator,
    loop,
    longPressActions: {}
  })
}

/**
 * 表单验证
 *
 * @export
 * @param {*} form 验证的数据
 * @param {*} list 验证属性列表  must:必填项  attr:属性名  placeholder/toast:提示文案  min:最小长度  tests:验证规则(mobile:手机号码  detectPassword:密码)
 * @param {*} fn 额外验证方法
 * @returns
 */
const tests = {
  mobile,
  detectPassword
}
export function formVerify(form, list, fn) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    const val = form[item.attr]
    const placeholder = item.placeholder
	const rules = item.rules || []

    if ((item.must || item.toast) && (!val && val !== 0)) {
      if (placeholder) toast(`请输入${placeholder}`)
      else toast(item.toast)
      return false
    }

    if (item.min && val.length < item.min) {
      toast(`${placeholder}不能小于${item.min}位`)
      return false
    }
	
	if (item.length && val.length !== item.length) {
		toast(`请输入${item.length}位${item.label}`)
		return false
	}

    if (val && item.test && !tests[item.test](val)) {
      toast(`${placeholder}格式不正确`)
      return false
    }
	
	if (val && rules.length > 0) {
		for (let i = 0; i < rules.length; i++) {
			const r = rules[i]
			if (!r.reg.test(val)) {
				toast(r.toast)
				return false
			}
		}
 	}
  }
  if (fn) {
    if (!fn()) return false
  }
  return true
}

// 复制数据
export function copyData(data) {
  const newDate = JSON.parse(JSON.stringify(data))
  return newDate
}

// 获取rpx转px值 默认底部悬浮按钮高度
export function px(num = 134) {
  return uni.upx2px(num)
}

// 拨打电话
export function cellPhone(phoneNumber) {
  uni.makePhoneCall({
    phoneNumber
  })
}

// 检查开始日期和结束日期有效性
export function checkDate(startDate, endDate) {
  if (startDate && endDate) {
    const start = new Date(startDate.replace(/-/g, '/')).getTime()
    const end = new Date(endDate.replace(/-/g, '/')).getTime()
    if (!(start && end)) return
    if (start > end) {
      toast('开始时间不能在结束时间之后')
      return false
    }
    return true
  }
  return false
}

export function getBetweenDatePrice(start, end, price, halfPrice) {
  const result = []
  const obj = {
    date: '',
    price: price,
    halfPrice: halfPrice
  }
  if (start === end) {
    const beginDay = start.split('-')
    obj.date = beginDay[0] + '-' + parseInt(beginDay[1]) + '-' + parseInt(beginDay[2])
    result.push(obj)
    return result
  }
  const beginDay = start.split('-')
  const endDay = end.split('-')
  const diffDay = new Date()
  const dateList = []
  let isOver = false
  diffDay.setDate(beginDay[2])
  diffDay.setMonth(beginDay[1] - 1)
  diffDay.setFullYear(beginDay[0])
  const begin = beginDay[0] + '-' + parseInt(beginDay[1]) + '-' + parseInt(beginDay[2])
  obj.date = begin
  result.push(obj)
  while (!isOver) {
    const obj = {
      date: '',
      price: price,
      halfPrice: halfPrice
    }
    const countDay = diffDay.getTime() + 24 * 60 * 60 * 1000
    diffDay.setTime(countDay)
    dateList[2] = diffDay.getDate()
    dateList[1] = diffDay.getMonth() + 1
    dateList[0] = diffDay.getFullYear()
    obj.date = dateList[0] + '-' + dateList[1] + '-' + dateList[2]
    result.push(obj)
    if (dateList[0] == endDay[0] && dateList[1] == endDay[1] && dateList[2] == endDay[2]) isOver = true
  }
  return result
}

export function numericTypeCheck(data,title){
	const numberRegex = /^\d+(\.\d{1,2})?$/;
	function toast(title = '数据校验有误，请重新输入'){
			uni.showToast({
			     title: title,
			     icon: 'none',
			     duration: 2000//持续的时间
			   })
		}
	if(data != '' && data){
		console.log(data)
		console.log(numberRegex.test(data))
		if(!numberRegex.test(data)){
			  toast(title)
			  return false
		}else{
			return true
		}
	}else{
		return true
	}
}


export function numberTypeCheck(data,title){
	const numberRegex = /^[1-9]\d*$|^0$/;
	function toast(title = '数据校验有误，请重新输入'){
			uni.showToast({
			     title: title,
			     icon: 'none',
			     duration: 2000//持续的时间
			   })
		}
	if(data != '' && data){
		console.log(data)
		console.log(numberRegex.test(data))
		if(!numberRegex.test(data)){
			  toast(title)
			  return false
		}else{
			return true
		}
	}else{
		return true
	}

}
/* const arr = preloadData.map(item => {
  return {
    width: item.width * 2,
    height: item.height * 2,
    left: item.left * 2,
    top: item.top * 2,
    skeletonType: item.skeletonType
  }
})
console.log('qwe', JSON.stringify(arr))*/
